import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'
import { apiGetUserInfo, apiMySelf } from '@/apis/user'
import { getToken, setToken } from '@/utils/auth';
// 定义 Store
export const useUserStore = defineStore(
  "user",
  () => {
    // 会员信息
    const userInfo = ref<any>();
    // 是否已经登录
    // let isLogin = !!getToken();

    const state = reactive({
      isLogin: !!getToken()
    });
    // 保存会员信息，登录时使用
    const setUserInfo = (val: any) => {
      userInfo.value = val
    }
    const editUSerDetail = () => {
      const detail = apiGetUserInfo();
      setUserInfo(detail);
    }

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      userInfo.value = undefined
    }
    // 登录
    const login = (user: any) => {
      // 标记登录成功
      state.isLogin = true;
      setToken(user.token);
      userInfo.value = user;
    }

    // 记得 return
    return {
      userInfo,
      setUserInfo,
      editUSerDetail,
      clearProfile,
      state,
      login
    }
  },
  // TODO: 持久化
  {
    persist: {
      storage: {
        getItem: uni.getStorageSync,
        setItem: uni.setStorageSync
      },
    },
  },
)
